package com.javastar.modules.pay.controller;

import cn.hutool.core.util.IdUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.javastar.common.annotation.Login;
import com.javastar.common.annotation.LoginUser;
import com.javastar.common.properties.AlipayProperties;
import com.javastar.modules.pay.service.AlipayService;
import com.javastar.modules.user.entity.UserEntity;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝支付接口
 *
 * @author zxx
 * @date 2023/7/26
 */
@RestController
@RequestMapping("pay/alipay")
@Api(tags = "支付宝支付")
public class AlipayController {
    @Autowired
    private AlipayProperties alipayProperties;
    @Autowired
    private AlipayService alipayService;

    @GetMapping("getPayForm")
    @ApiOperation(value = "获取支付表单页面", notes = "&subject=xxx&traceNo=xxx&totalAmount=xxx，需要登录")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "totalAmount", value = "支付总金额", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "subject", value = "支付标题", required = true, paramType = "query", dataType = "string")
    })
    @ApiResponse(code = 200, message = "支付表单页面")
    @Login
    public void getPayForm(@ApiIgnore @RequestParam Map<String, Object> params, @ApiIgnore HttpServletResponse httpResponse, @ApiIgnore @LoginUser UserEntity user) throws Exception {
        // 生成订单号、根据用户信息生成订单、生成订单对应商品...
        String orderNo = IdUtil.fastUUID();

        // 设置应用信息
        AlipayClient alipayClient = new DefaultAlipayClient(alipayProperties.getGatewayUrl(), alipayProperties.getAppId(),
                alipayProperties.getAppPrivateKey(), alipayProperties.getFormat(), alipayProperties.getCharset(), alipayProperties.getAlipayPublicKey(), alipayProperties.getSignType());
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // 设置回调地址
        request.setNotifyUrl(alipayProperties.getNotifyUrl());
        request.setBizContent("{\"out_trade_no\":\"" + orderNo + "\"," // 订单号
                + "\"total_amount\":\"" + params.get("totalAmount") + "\"," // 支付总金额
                + "\"subject\":\"" + params.get("subject") + "\"," // 支付标题
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + alipayProperties.getCharset());
        httpResponse.getWriter().write(form); // 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @PostMapping("alipayNotify")
    @ApiOperation(value = "支付宝异步回调通知")
    @ApiOperationSupport(order = 2)
    public void alipayNotify(HttpServletRequest request) throws Exception {
        // 支付成功
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }
            // 订单号
            String orderNo = params.get("out_trade_no");
            // 交易号
            String tradeNo = params.get("trade_no");
            // 付款时间
            String gmtPayment = params.get("gmt_payment");
            // 付款金额
            String buyerPayAmount = params.get("buyer_pay_amount");
            // 交易主题 - 后续根据不同交易主题进行不同的处理
            String subject = params.get("subject");
//            System.out.println("交易名称: " + params.get("subject"));
//            System.out.println("交易状态: " + params.get("trade_status"));
//            System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
//            System.out.println("商户订单号: " + params.get("out_trade_no"));
//            System.out.println("交易金额: " + params.get("total_amount"));
//            System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
//            System.out.println("买家付款时间: " + params.get("gmt_payment"));
//            System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
            // 修改订单状态、进行进一步处理...
        }
    }
}
